package cn.xiaobai.service.impl;

import cn.hutool.json.JSONUtil;
import cn.xiaobai.domain.HotModel;
import cn.xiaobai.service.HotKeyCustomService;
import cn.xiaobai.utils.ConfigReadUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * @Author yangdaji
 * @Date 2022/10/12 0012
 * @PackageName cn.xiaobai.service.impl
 * @ClassName HotKeyCustomServiceImpl
 */
public class HotKeyCustomServiceImpl implements HotKeyCustomService {


    @Value("${hotkey.config:}")
    private String hotkeyConfig;

    /**
     * 运行参数名称
     */
    @Value("${args.name:}")
    private String argsName;

    @Autowired
    private ApplicationArguments applicationArguments;

    @Override
    public Optional<HotModel> getHotModel() {
        if (Strings.isBlank(hotkeyConfig)) {
            return Optional.empty();
        }
        List<String> optionValues = applicationArguments.getOptionValues(argsName);
        if (CollectionUtils.isEmpty(optionValues)) {
            String hotKeyJson = ConfigReadUtils.readConfigFile(hotkeyConfig);
            return jsonToHotModel(hotKeyJson);
        } else {
            // 针对jar包使用外部 json 配置时
            String hotKeyJson = ConfigReadUtils.readConfigFile(optionValues.get(0));
            return jsonToHotModel(hotKeyJson);
        }
    }

    private Optional<HotModel> jsonToHotModel(String json) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        HotModel hotModel = JSONUtil
                .toBean(json, HotModel.class);
        return Optional.of(hotModel);
    }

}
